//
//  NetworkTools.swift
//  SinaWeibo
//
//  Created by 张子国 on 15/11/19.
//  Copyright © 2015年 张子国. All rights reserved.
//

import UIKit
import AFNetworking

private let  weiboDomain = "com.baidu.data.error"
private let hostname = "https://api.weibo.com/"
//private let hostname = "https://test.weibo.com/"


enum HTTPMethod : String{
    case POST = "POST"
    case GET = "GET"
}

class NetworkTools: AFHTTPSessionManager {
    
    //定义单例对象
    static let sharedTools: NetworkTools = {
 //      let urlString = "https://api.weibo.com/"

        let url = NSURL(string: hostname)
        let tools = NetworkTools(baseURL: url)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()


func requestJsonDict(method: HTTPMethod, urlString: String, parameters: [String : AnyObject]?, finished:(result: [String : AnyObject]?,error : NSError?) -> ())  {
    if method == HTTPMethod.GET {
        GET(urlString, parameters : parameters, success: { (_, result) -> Void in
            if let dict = result as? [String : AnyObject] {
                finished(result: dict, error: nil)
                return
            }
        
            let dataError = NSError(domain: weiboDomain, code: -22222, userInfo: [NSLocalizedDescriptionKey:"数据错误"])
            finished(result: nil, error: dataError)
            }) { (result, error) -> () in
                finished(result:nil , error: error)
                print(error)
    }
            } else {
            POST(urlString, parameters: parameters, success: { (_, result) -> Void in
                if let dict = result as? [String : AnyObject] {
                    finished(result: dict, error: nil)
                    return
                }
                let dataError = NSError(domain: weiboDomain, code: -33333, userInfo: [NSLocalizedDescriptionKey:"数据错误"])
                
                finished(result: nil, error: dataError)
                }) {(result,error) ->() in
                    finished(result: nil, error: error)
                    print(error)
        }
    
 }
}
}
